<script setup lang="tsx">
import { ref, shallowRef, onBeforeUnmount, defineProps, defineEmits } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useUserStoreWithOut } from '@/store/modules/user'
import { ElMessage } from 'element-plus'

const PATH_URL = import.meta.env.VITE_API_BASE_PATH

// Props
const props = defineProps({
  placeholder: {
    type: String,
    default: '<p>请输入内容</p>'
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'created'])

const mode = ref('default')

// 编辑器内容
const content = ref('')

// 编辑器实例
const editorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {}

// 编辑器配置
const editorConfig = {
  placeholder: props.placeholder,
  MENU_CONF: {}
}

type InsertFnType = (url: string, alt?: string, href?: string) => void
editorConfig.MENU_CONF['uploadImage'] = {
  server: PATH_URL + '/fileTransferFile/upload.adw',
  fieldName: 'file',
  maxFileSize: 1 * 1024 * 1024, // 1MB
  maxNumberOfFiles: 10,
  allowedFileTypes: ['image/*'],
  headers: {
    Authorization: useUserStoreWithOut().getToken
  },
  meta: {
    moduleName: 'forumPost'
  },
  customInsert(res: any, insertFn: InsertFnType) {
    const url = res.data?.url || 'http://itdct.com:3100/itdct-dev/' + res.data
    insertFn(url)
  },
  onFailed(file: File, res: any) {
    ElMessage.error(res)
  },
  onError(file: File, err: any, res: any) {
    console.log(`${file.name} 上传出错`, err, res)
    ElMessage.error(err.message)
  }
}

// 当编辑器创建完成
const handleCreated = (editor) => {
  editorRef.value = editor
  emit('created', editor)
}

// 销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 向外同步内容
emit('update:modelValue', content.value)

const getContent = () => {
  return content.value
}

const setContent = (value) => {
  content.value = value
}
defineExpose({
  getContent,
  setContent
})
</script>

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="content"
      :defaultConfig="editorConfig"
      :mode="mode"
      @on-created="handleCreated"
    />
  </div>
</template>
<style scoped lang="less"></style>
